/**
 * Created by shaoyin.zj on 16/12/24.
 */
var request = require('request');
// hubot聊天页面
var Hubot = require('../hubot');
var hubot = new Hubot();
const WebSocket = require('../websocket');
const webSocket = new WebSocket();

// 向http adapter发送用户输入内容
var send_talk = async (ctx, next) => {
    var message = ctx.params.message;
    hubot.send('1',message);
    
};

// 机器人聊天页面
var talk_view = async (ctx, next) => {
	ctx.render("talk", {name:'alice', aaa:ctx.params.aaa});
}

// http adapter回调地址
var adapter_back = async (ctx, next) => {
	var rm = ctx.request.body,
		from = rm.from,
		message = rm.message;
	// 主动向前端推送答案
	webSocket.send(ctx.params.room,message);
};

var tuling_test = async (ctx, next) => {
	var room = ctx.params.room,
		message = ctx.params.message;
	ctx.response.body = await getAnwserFromTuling(room, message);
}

var tuling = async (ctx, next) => {	
	var rm = ctx.request.body,
		room = rm.room,
		message = rm.message;
	console.log(JSON.stringify(rm));
	try{
		ctx.response.body = await getAnwserFromTuling(room, message);
		// var result = await getAnwserFromTuling(room, message);
		// switch (result.code){
		// 	// 文本类
		// 	case '100000':
		// 		ctx.response.body = result.text;
		// 		break;
		// 	// 链接类
		// 	case '200000':
		// 		ctx.response.body = result.text + '<br>' + result.url;
		// 		break;
		// 	// 新闻类
		// 	case '302000':
		// 		var news_length = result.list.length;
		// 		ctx.response.body = result.text;
		// 		if(news_length){
		// 			for(var i=0; i< news_length; i++){
		// 				ctx.response.body = ctx.response.body + '<br>' + result.list[i].article + " " + result.list[i].detailurl;
		// 			}
		// 		}
		// 		break;
		// 	// 菜谱类
		// 	case '308000':
		// 		var menu_length = result.list.length;
		// 		ctx.response.body = result.text;
		// 		if(news_length){
		// 			for(var i=0; i< menu_length; i++){
		// 				ctx.response.body = ctx.response.body + '<br>' + result.list[i].name + " " + result.list[i].info + " " + result.list.detailurl;
		// 			}
		// 		}
		// 		break;
		// 	// 儿歌类 - 儿童版
		// 	case '313000':				
		// 		break;
		// 	// 诗词类 - 儿童版
		// 	case '314000':
		// 		break;
		// 	default:
		// 		break;
		// }
	} catch(err) {
		console.log(err);
	}
};

// 调用图灵机器人api
var getAnwserFromTuling = function(userid, message){
	var tuling_api = "http://www.tuling123.com/openapi/api",
		api_key = "db484da30461408abe46b24e6899eda2",
		sceret = "ea237af06af95e71",
		data = {
			"key": api_key,
			"info": message,
			"loc": "",
			"userid": userid
		};
	return new Promise(function (resolve, reject){
		// request.post异步执行
		request.post(tuling_api, {'form': data}, function(error, response, body){
			resolve(body);
		});
	});
};


module.exports = {
    'GET /talk': talk_view,
    'POST /sendTalk': send_talk,
    'POST /adapter_back/:room': adapter_back,
    'GET /tuling-test/:room/:message': tuling_test,
    'POST /tuling': tuling
};